package com.star.spring.auth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    // Security详细配置
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 自定义表单登录
        http.formLogin(form -> {
            form
//                    .loginPage("/login.html")// 自定义登录页面
//                    .usernameParameter("username") // 表单中的用户名项
//                    .passwordParameter("password")
//                    .loginProcessingUrl("/login") //登录路径，表单向该路径提交，提交后自动执行UserDetailsService的方法
                    .successForwardUrl("/main.html") //登录成功后跳转的路径
                    .failureForwardUrl("/fail.html"); //登录失败后跳转的路径

        });


        // 需要认证的资源
        http.authorizeHttpRequests(resp -> {

            resp.requestMatchers("/login.html", "/fail.html").permitAll(); // 不需要认证的资源
            resp.requestMatchers("/css/*.css", "/js/*.js", "/img/**").permitAll(); // 静态资源不需要认证
            resp.anyRequest().authenticated();//其余所有请求都需要认证
        });


        // 关闭csrf防护
        http.csrf(csrf -> {
            csrf.disable();
        });
        return http.build();
    }

    //密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
